package com.xx.jicheng.service.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xx.jicheng.mapper.ConfigMapper;
import com.xx.jicheng.service.ConfigService;

@Service("configService")
public class ConfigServiceImpl implements ConfigService {
	
	@Autowired
	private ConfigMapper configMapper;
	
	private ObjectMapper mapper = new ObjectMapper();
	
	@Autowired
	@Qualifier("commonRedisTemplate")
	private RedisTemplate<String, Object> template;

	@Override
	public String findByName(String name) {
		String json = configMapper.findByName(name);
		template.boundValueOps(name).set(json);
		return json;
	}

	@Override
	public void update(String name, String json) {
		configMapper.update(name, json);
		template.delete(name);
	}
	
	@Override
	public boolean isCacheEnabled(String cache){
		try {
			String json = findByName("cache.config");		
			Map<String,Boolean> map = mapper.readValue(json, new TypeReference<Map<String,Boolean>>() { });
			if(map.containsKey(cache)) {
				return map.get(cache);
			}
			return false;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
